import React from 'react';
import { connect } from 'dva';
import { Modal, Spin } from 'antd';
import BasicInformation from './basicInformation';

@connect(
  state => ({
    loadingupdate: state.loading.effects['taskMngt/update'],
    loadingqueryAuditTaskInfo: state.loading.effects['taskMngt/queryAuditTaskInfo'],
    dataqueryAuditTaskInfo: state.taskMngt.dataqueryAuditTaskInfo,
  }),
  dispatch => ({
    update: e => dispatch({ type: 'taskMngt/update', payload: e }),
    queryAuditTaskInfo: e => dispatch({ type: 'taskMngt/queryAuditTaskInfo', payload: e }),
    savequeryAuditTaskInfo: e => dispatch({ type: 'taskMngt/savequeryAuditTaskInfo', payload: e }),
  })
)
export default class Edit extends React.Component {
  state = {
    modalVisible: false,
  };
  handleModalVisible = () => {
    if (this.props.disabled) return;
    if (!this.state.modalVisible) this.props.queryAuditTaskInfo({ executionPolicyId: this.props.executionPolicyId });
    if (this.state.modalVisible) this.props.savequeryAuditTaskInfo({});
    this.setState(() => ({ modalVisible: !this.state.modalVisible }));
  };
  confirmAdd = () => {
    this.basicInformation.props.form.validateFields((err, values) => {
      if (err) return;
      this.props
        .update({
          executionPolicyId: this.props.executionPolicyId,
          ...values,
          executionTime:
            values.executionTime &&
            (values.executionCycleTypeId == 2
              ? values.executionTime.format('YYYY-MM-DD HH:mm:ss')
              : values.executionTime.format('HH:mm')),
          restaskDbGroupPos: JSON.stringify(
            values.restaskDbGroupPos.map(item => JSON.parse(item))
          ),
        })
        .then(res => {
          if (res.rescode == 200) {
            Modal.success({ title: '操作成功' });
            this.handleModalVisible();
            this.props.pageList();
          } else if (res.rescode == 205) {
            Modal.warning({ title: '操作告警', content: res.msg });
          } else {
            Modal.error({ title: '操作失败', content: res.msg });
          }
        });
    });
  };
  render() {
    return (
      <>
        <Modal
          title="编辑任务"
          visible={this.state.modalVisible}
          onCancel={this.handleModalVisible}
          destroyOnClose
          maskClosable={false}
          confirmLoading={this.props.loadingupdate}
          onOk={this.confirmAdd}
          width={640}
        >
          <Spin spinning={Boolean(this.props.loadingqueryAuditTaskInfo)}>
            <BasicInformation
              {...this.props}
              getInstance={childCp => {
                this.basicInformation = childCp;
              }}
              initialData={this.props.dataqueryAuditTaskInfo}
            />
          </Spin>
        </Modal>
        <span onClick={this.handleModalVisible}>{this.props.children}</span>
      </>
    );
  }
}
